package coml.jiyun.hp.reviewtopic.ui.activity;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import coml.jiyun.hp.reviewtopic.CircleProgressBar;
import coml.jiyun.hp.reviewtopic.R;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class DownActivity extends AppCompatActivity implements View.OnClickListener {

    /**
     * 0%
     */
    private CircleProgressBar mCpb;
    /**
     * 下载
     */
    private Button mDownBtnDown;
    /**
     * 安装
     */
    private Button mDownBtnInstall;

    /**
     * 安装
     */
    private boolean down;
    private String url = "https://gitee.com/xts123/api/raw/master/app-release.apk";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_down);
        initView();
    }

    private void initView() {
        mCpb = (CircleProgressBar) findViewById(R.id.cpb);
        mDownBtnDown = (Button) findViewById(R.id.down_btn_down);
        mDownBtnDown.setOnClickListener(this);
        mDownBtnInstall = (Button) findViewById(R.id.down_btn_install);
        mDownBtnInstall.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            default:
                break;
            case R.id.down_btn_down:
                String path = "内部存储/a.apk";
                download(url, path);
                initload();
                break;
            case R.id.down_btn_install:

                break;
        }
    }

    private void download(String url, final String path) {
        Request request = new Request.Builder()
                .get()
                .url(url)
                .build();
        new OkHttpClient()
                .newCall(request)
                .enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Log.d("TAG", "onFailure: "+e.toString());
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        //请求成功
                        Log.d("TAG", "onResponse: ");
                        InputStream inputStream = response.body().byteStream();
                        saveFile(path, inputStream, response.body().contentLength());
                    }
                });
        }

    private void saveFile(String file, InputStream inputStream, long max) {
        byte[] bytes = new byte[1024];
        int len = 0;
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(file);
            while ((len = inputStream.read(bytes)) != -1) {
                fileOutputStream.write(bytes, 0, len);
            }
            Log.d("TAG", "下载成功");

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关流
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (fileOutputStream != null) {
                    fileOutputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    mDownBtnInstall.setVisibility(View.VISIBLE);
                }
            });
        }
    }

    private void initload() {
        if (!down) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    for (int i = 0; i < 101; i++) {
                        try {
                            Thread.sleep(20);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        down = true;
                        if (i == 100) {
                            down = false;
                        }
                        mCpb.setProgress(i);
                    }
                }
            }).start();
        }
    }
}